<?php

namespace App\Admin\Forms;

use App\Models\RechargeRecord;
use App\Models\User;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class UserProfile extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * @param array $input
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function handle(array $input)
    {
        $id = $this->payload['key'] ?? 0;
        $info = RechargeRecord::query()->find($id);
        $user_id = $info->user_id;
        $price = $input['price'];
        $user = User::query()->find($user_id);
        $this->log($user, $price);
        User::query()->where('id', $user_id)->update(['balance' => DB::raw('balance +' . $price)]);
        return $this->success('充值成功');
    }

    public function form()
    {
        $this->number('price', '金额')->required()->help('充值金额');
    }

    /**
     * @param object $user
     * @param $price
     * @return bool
     * 充值流水
     */
    public function log(object $user, $price)
    {
        $sn = uniqid('B');
        $recharge_record = new RechargeRecord();
        $recharge_record->user_id = $user->id;
        $recharge_record->price = $price;
        $recharge_record->status = 1;
        $recharge_record->order_sn = $sn;
        $recharge_record->sn = '4200000' . rand(111, 999) . date('YmdHis') . rand(1111, 9999);
        $recharge_record->sn_number = 5 . date('YmdHi') . str_pad(1, 5, '0', STR_PAD_LEFT);;
        $recharge_record->note = '余额充值';
        $recharge_record->type = 1; //微信充值
        $recharge_record->after_price = bcadd($user->balance, $price, 2); //充值后金额
        $recharge_record->amount = $user->balance; //充值前金额
        $recharge_record->company_id = $user->company_id; //公司ID
        if ($recharge_record->save()) {
            return true;
        };
        return false;
    }
}